import MySQL


def read(file_name):
    f = open(file_name, 'r')
    rows = f.readlines()
    f.close()
    return rows


def resolve(date):
    count = {}
    for i in range(ord('a'), ord('z') + 1):
        count[chr(i)] = 0
    for hour in range(24):
        file_name = '../data/wiki/project/projectcounts-{date}-{hour}0000'.format(date=date, hour='%02d' % hour)
        rows = read(file_name)
        for row in rows:
            count[row[0]] = count[row[0]] + int(row.split()[2])
    for i in range(ord('a'), ord('z') + 1):
        MySQL.save('project_count', {
            'date': date,
            'group': chr(i),
            'group_len': 1,
            'count': count[chr(i)]
        })


def resolve2(date, hour):
    count = {}
    file_name = '../data/wiki/project/projectcounts-{date}-{hour}0000'.format(date=date, hour='%02d' % hour)
    rows = read(file_name)
    for row in rows:
        group = row.split()[0].split('.')[0]
        if group not in count:
            count[group] = 0
        count[group] = count[group] + int(row.split()[2])
    for k, v in count.items():
        MySQL.save('hour_count_2', {
            'date': date,
            'hour': hour,
            'group': k,
            'count': v
        })


if __name__ == '__main__':
    MySQL.init('wiki')
    for year in range(2016, 2017):
        for month in range(1, 2):
            for day in range(1, 31):
                for hour in range(24):
                    resolve2('{year}{month}{day}'.format(year=year, month='%02d' % month, day='%02d' % day), hour)
